/**
 * Sequencer
 * <p/>
 * User: joakimd
 * Date: 2013-04-12
 * Time: 11:25
 */
package org.dru.masic.trix {
public class Sequencer {
    private var _samples: Samples;
    private var _sequence: Vector.<Vector.<int>>;
    private var _songPos: int;
    private var _samplePos: int;
    private var _nextPos: int;
    private var _samplePos2:int;

    public function Sequencer(samples: Samples) {
        _samples = samples;
        _sequence = new Vector.<Vector.<int>>();
        _sequence.push(seq1());
        _sequence.push(seq2());
        _songPos = 0;
        _samplePos = 0;
        _samplePos2 = 0;
        _nextPos = 0;
    }

    private static function seq1(): Vector.<int> {
        var tracks: Vector.<int> = new Vector.<int>();
        tracks.push(1);
        tracks.push(2);
        tracks.push(0);
        tracks.push(3);
        tracks.push(0);
        return tracks;
    }

    private static function seq2(): Vector.<int> {
        var tracks: Vector.<int> = new Vector.<int>();
        tracks.push(4);
        tracks.push(5);
        tracks.push(6);
        tracks.push(7);
        tracks.push(8);
        return tracks;
    }

    public function set nextPos(value: int): void {
        _nextPos = value;
    }

    public function work(left: Vector.<Number>, right: Vector.<Number>, offset: int, length: int): void {
        do {
            var amount: int = Math.min(length, 235200 - _samplePos2);
            if (amount == 0) {
                _songPos = _nextPos;
                _samplePos2 = 0;
            } else {
                var seq: Vector.<int> = _sequence[_songPos];
                var sample: ISample = _samples.getSample(seq[0]);
                sample.copyTo(_samplePos, left, right, offset, amount);
                var max: int = sample.length;
                for (var track: int = 1; track < seq.length; track++) {
                    sample = _samples.getSample(seq[track]);
                    sample.addTo(_samplePos, left, right, offset, amount);
                }
                _samplePos += amount;
                _samplePos2 += amount;
                if (_samplePos == 470400) {
                    _samplePos = 0;
                }
                length -= amount;
            }
        }
        while (length > 0);
    }
}
}
